package practice.phase03.module04.zookeeper.distlock;

import org.I0Itec.zkclient.ZkClient;

/**
 * DistLockTest.java
 * zk实现分布式锁
 *
 * @author Alex Zhang
 */
public class DistLockTest {
    public static void main(String[] args) {
        // 使用10个线程模拟分布式环境
        String lockPath = "/distlocks";
        ZkClient zk = new ZkClient("n1:2181,n2:2181");
        if(!zk.exists(lockPath)) {
            zk.createPersistent(lockPath);
        }
        final int numOfUsers = 10;
        for (int i = 0; i < numOfUsers; i++) {
            (new Thread(new DistLockRunnable())).start();
        }
    }
    private static class DistLockRunnable implements Runnable {

        @Override
        public void run() {
            // 每个线程抢锁
            final DistClient distClient = new DistClient();
            distClient.getDistLock();
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            distClient.releaseLock();
        }
    }
}
